package gatperdut.chato.core.interpreter.actions;

import gatperdut.chato.constants.CSConstantsCommandResult.CommandExecutionResult;
import gatperdut.chato.constants.CSConstantsString;
import gatperdut.chato.core.characters.BaseController;
import gatperdut.chato.core.interpreter.actions.generic.AdminAction;
import gatperdut.chato.core.interpreter.grammar.comminfo.ListItemTemplatesInfo;
import gatperdut.chato.model.Chato.Item.ItemTemplate;

import java.util.List;

public class ListItemTemplatesAction extends AdminAction {

    public ListItemTemplatesAction( ListItemTemplatesInfo info, BaseController entityController ) {
        super( info, entityController );
    }

    @Override
    public CommandExecutionResult perform() {
        checkForRunningCraft();

        AdminCheckResult acr = checkAdminUser();
        if ( !acr.isAllowed() ) {
            getEntityController().tx( acr.getMessage() );
            return CommandExecutionResult.OK;
        }

        List<ItemTemplate> results = getEntityController().getChatoServer().getItemTemplateHandler().findByKeywords( getInfo().getKeywords() );

        if ( results.isEmpty() ) {
            getEntityController().tx( "No item templates matching those keywords could be found." );
            return CommandExecutionResult.OK;
        }

        StringBuilder sb = new StringBuilder( results.size() + " matches:" + CSConstantsString.NEWLINE );
        for ( ItemTemplate result : results ) {
            sb.append( "<" + result.hashCode() + "> - " + result.getShortDesc() + CSConstantsString.NEWLINE );
        }

        getEntityController().tx( sb.toString() );

        return CommandExecutionResult.OK;
    }

    @Override
    public ListItemTemplatesInfo getInfo() {
        return (ListItemTemplatesInfo) super.getInfo();
    }

}
